﻿//************************************************************************************************
// Copyright © 2004-2012 Steven M. Cohn. All Rights Reserved.
//
// Stolen and customized from Scout!  (Which I wrote, so I guess it's not really stealing)
//
//************************************************************************************************ 

namespace CookieChipper
{
	using System;
	using System.Diagnostics.CodeAnalysis;
	using System.IO;
	using System.Runtime.InteropServices;
	using System.Text;


	internal static class IniProvider
	{
		private const int MaxKeySize = 255;


		[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
		[DllImport("kernel32", CharSet = CharSet.Unicode)]
		private static extern int GetPrivateProfileString (
			string section,			// name of section, if null all names are retrieved
			string key,				// name of key to read, if null all key names are retrieved
			string def,				// default string if key not found, null is same as empty
			StringBuilder retVal,	// buffer to receive retrieved string
			int size,				// size of return string buffer in chars
			string filePath);		// name of ini file, if no path then C:\Windows


		/// <summary>
		/// Retieves the value of the named key from the specified file
		/// </summary>
		/// <param name="section"></param>
		/// <param name="key"></param>
		/// <returns></returns>

		public static string Read (string path, string section, string key)
		{
			if (!File.Exists(path))
			{
				return null;
			}

			try
			{
				var buffer = new StringBuilder(MaxKeySize);
				int len = GetPrivateProfileString(section, key, null, buffer, MaxKeySize, path);
				return len == 0 ? String.Empty : buffer.ToString();
			}
			catch
			{
				return String.Empty;
			}
		}
	}
}
